package com.tzy.dishes.controller;
import com.tzy.common.constant.WebResult;
import com.tzy.common.constant.WebResultMsgCode;
import com.tzy.common.controller.BaseController;
import com.tzy.common.entity.Dishes;
import com.tzy.common.utils.UpPhotoNameUtils;
import com.tzy.dishes.service.DishesService;
import com.tzy.dishes.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * https://blog.csdn.net/YINLINNEVERG/article/details/80250945
 */
@RestController
@Slf4j
@RequestMapping("/dishes")
public class FileUploadController extends BaseController {
    @Value("${file.upload.url}")
    private String uploadUrl;//文件上传路径
    @Value("${file.upload.prefix-url}")
    private String prefixUrl;//服务器路径前缀
    @Resource
    private DishesService dishesService;
    @Resource
    private RedisService redisService;

    /**
     * 上传图片或视频到服务器; 配置nginx作为图片&视频服务器(可选功能)
     * 单文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public WebResult singleFileUpload(@RequestParam("file") MultipartFile file,
                                      HttpServletRequest request) throws IOException {
//        int uid = getUid(request);
//        log.info("uid=" + uid);
        //@RequestParam("file") MultipartFile file为接收图片参数
        //Integer userId,String status 用户Id和状态
        byte[] bytes = file.getBytes();
        String imageFileName = file.getOriginalFilename();
        log.info("imageFileName=" + imageFileName);
        String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
        log.info("fileName=" + fileName);
        //“D:\idea-project2\PinTu\src\main\resources\static\assets\”为本地目录
        //路径不要写死了, 要引用配置文件的
        Path path = Paths.get(uploadUrl + fileName);
        Files.write(path, bytes);//写入文件
        //把图片名称写入数据库
        //路径不要写死了, 要引用配置文件的
        log.info("prefixUrl=" + prefixUrl);
        String dishesPhotoOrVideoUrl = prefixUrl + fileName;
        redisService.setString("dishesPhotoOrVideoUrl",dishesPhotoOrVideoUrl,120);
        log.info("dishesPhotoOrVideoUrl" + dishesPhotoOrVideoUrl);
//            Dishes dishes = new Dishes();
//            dishes.setDishesPhotoOrVideoUrl(dishesPhotoOrVideoUrl);

        return new WebResult(WebResultMsgCode.SUCCESS, dishesPhotoOrVideoUrl);
    }
    @GetMapping("/url")
    public WebResult getUrl(){
        return new WebResult(WebResultMsgCode.SUCCESS,redisService.getString("dishesPhotoOrVideoUrl"));
    }

    /**
     * 接收多文件上传
     *
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping("/upload/multipart/file")
    public WebResult doUpload(MultipartFile[] files) throws IOException {
        for (MultipartFile file : files) {
            byte[] bytes = file.getBytes();
            log.info("fileName=" + file.getName());
            String imageFileName = file.getOriginalFilename();
            log.info("imageFileName=" + imageFileName);

            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            log.info("fileName=" + fileName);
            //“D:\idea-project2\PinTu\src\main\resources\static\assets\”为本地目录
            //路径不要写死了, 要引用配置文件的
            Path path = Paths.get(uploadUrl + fileName);
            Files.write(path, bytes);//写入文件
            //把图片名称写入数据库
            //路径不要写死了, 要引用配置文件的
            log.info("prefixUrl=" + prefixUrl);
            String fileUrl = prefixUrl + fileName;
            log.info("fileUrl" + fileUrl);
//            User user = new User();
//            user.setId(uid);
//            user.setProfilePhoto(fileUrl);//头像
//            //修改用户头像
//            userService.updateById(user);
            Dishes dishes = new Dishes();
            dishes.setDishesPhotoOrVideoUrl(fileUrl);
            boolean updateById = dishesService.updateById(dishes);
            //返回文件名字
            return new WebResult(WebResultMsgCode.SUCCESS).putData("fileName", fileName);
        }
        return new WebResult(WebResultMsgCode.FAIL);
    }
//    /**
//     * 一定要是GetMapping
//     * @return
//     */
//    @GetMapping("/toUpload")
//    public String toUpload(){
//        System.out.println("正在前往toUpload");
//        //跳转视图
//        return "manager/upload/toUpload";
//    }
//    /**
//     * 接收多文件上传
//     * @param files
//     * @return
//     * @throws IOException
//     */
//    @PostMapping("/doUpload")
//    public String doUpload( MultipartFile[] files /*,
//                            @RequestParam String name,
//                            @RequestParam int age*/ ) throws IOException {
//        System.err.println("doUpload()");
//        for (MultipartFile file:files ) {
//            final String fileName1 = file.getName();
//            //System.out.println("size"+file.getSize());
//            //获取 原始文件的名字
//            String fileName = file.getOriginalFilename();//错误方式 : file.getName();
//            System.out.println("fileName = "+fileName);
//            //System.out.println("name="+ fileName.substring(fileName.lastIndexOf(".")) );
//            String ext = fileName.substring(fileName.lastIndexOf("."));
//
//            long curTime = System.currentTimeMillis();
//            System.out.println("curTime = "+curTime);
//            Path path = Paths.get("d:", "upload"+ext);
//            System.out.println("path = "+path);
//            //创建文件夹
//            if(!Files.exists(path)){
//                Files.createDirectory(path);
//            }
//
//            //String fileNewName = File.separator+"upload"+File.separator+curTime+ext;
//            //file.transferTo(Paths.get("/","upload",fileName));
//            //upload文件需要手动创建(代码创建 : file.mkdir())//最后那里是逗号,不是加号+
//            file.transferTo(Paths.get("d:","upload",String.valueOf(curTime)+ext));;
//        }
//
//        //跳转视图
//        return "WEB-INF/jsp/success";
//    }

    //    /**
//     * 接收单文件上传
//     * @param file
//     * @return
//     * @throws IOException
//     */
//    @PostMapping("/doUpload")
//    public String doUpload(MultipartFile file) throws IOException {
//        //System.out.println("size"+file.getSize());
//        //获取 原始文件的名字
//        String fileName = file.getOriginalFilename();//错误方式 : file.getName();
//        System.out.println("fileName = "+fileName);
//        //System.out.println("name="+ fileName.substring(fileName.lastIndexOf(".")) );
//        String ext = fileName.substring(fileName.lastIndexOf("."));
//
//        long curTime = System.currentTimeMillis();
//        System.out.println("curTime = "+curTime);
//        Path path = Paths.get("d:", "upload"+ext);
//        System.out.println("path = "+path);
//        //创建文件夹
//        if(!Files.exists(path)){
//            Files.createDirectory(path);
//        }
//
//        //String fileNewName = File.separator+"upload"+File.separator+curTime+ext;
//        //file.transferTo(Paths.get("/","upload",fileName));
//        //upload文件需要手动创建(代码创建 : file.mkdir())//最后那里是逗号,不是加号+
//        file.transferTo(Paths.get("d:","upload",String.valueOf(curTime)+ext));;
//        //跳转视图
//        return "WEB-INF/jsp/success";
//    }

//    @PostMapping("/uploads")
//    public String uploadsByPost(Model model, HttpServletRequest request) {
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
//        for (MultipartFile file : files) {
//            if (!file.isEmpty()) {
//                try {
//                    String filePath = PathUtil.uploadPath + file.getOriginalFilename();
//                    BufferedOutputStream out = new BufferedOutputStream(
//                            new FileOutputStream(new File(filePath)));
//                    out.write(file.getBytes());
//                    out.flush();
//                    out.close();
//                    model.addAttribute("msg", "上传文件成功");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    model.addAttribute("msg", "上传文件失败：" + e.getMessage());
//                }
//            } else {
//                model.addAttribute("msg", "上传文件失败：文件为空");
//            }
//        }
//
//        return "uploads";
//    }

//    @PostMapping("/upload")
//    public String uploadByPost(Model model,
//                               @RequestParam("file") MultipartFile file) {
//        if (!file.isEmpty()) {
//            try {
//                String filePath = PathUtil.uploadPath + file.getOriginalFilename();
//                log.info("filePath=" + filePath);
//                BufferedOutputStream out = new BufferedOutputStream(
//                        new FileOutputStream(new File(filePath)));
//                out.write(file.getBytes());
//                out.flush();
//                out.close();
//                model.addAttribute("msg", "上传文件成功");
//            } catch (Exception e) {
//                e.printStackTrace();
//                model.addAttribute("msg", "上传文件失败：" + e.getMessage());
//            }
//        } else {//文件上传失败的消息提示
//            model.addAttribute("msg", "上传文件失败：文件为空");
//        }
//        return "upload";
//    }
}
